package top.yonyong.myredis.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yonyong.myredis.distributelock.RedisDistributeLock;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Describtion Todo
 * @Author yonyong
 * @Date 2020/6/29 10:21
 * @Version 1.0.0
 **/
@RestController
@RequestMapping("test")
public class RedisController {

    public static final String REDIS_LOCK_KEY = "lock_key";

    @Resource
    RedisDistributeLock redisDistributeLock;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @PostMapping("stock-count-down")
    public Object lock() throws InterruptedException {
        Map<String,Object> map = new HashMap<>(2);
        List<String> list = new ArrayList<>();
        String requestId = UUID.randomUUID().toString();
        final String lockStatus = redisDistributeLock.lock(REDIS_LOCK_KEY, requestId, 300);

        if (StringUtils.equals(requestId,lockStatus)){

            list.add("加锁成功:" + lockStatus);
            Thread.sleep(3000);
            //库存减一
            RedisAtomicLong atomicLong = new RedisAtomicLong("stock",stringRedisTemplate.getConnectionFactory());
            final long andDecrement = atomicLong.decrementAndGet();
            list.add("剩余库存:" + andDecrement);

            //释放锁
            final boolean unLockStatus = redisDistributeLock.unLock(REDIS_LOCK_KEY, requestId);
            list.add("解锁成功:" + unLockStatus);

            map.put("result","SUC");
        }else {
            list.add("获取锁失败");

            map.put("result","FAL");
        }

        map.put("process",list);
        return map;
    }
}
